package com.iteaj.iot.test.mqtt;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.iteaj.iot.AbstractProtocol;
import com.iteaj.iot.ProtocolFactory;
import com.iteaj.iot.client.mqtt.MqttConnectProperties;
import com.iteaj.iot.client.mqtt.impl.MqttDefaultClientMessage;
import com.iteaj.iot.client.mqtt.impl.MqttDefaultImplProcessor;
import com.iteaj.iot.client.mqtt.message.MqttMessageHead;
import com.iteaj.iot.test.TestProtocolType;
import com.iteaj.iot.utils.ByteUtil;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.handler.codec.mqtt.MqttTopicSubscription;

import java.util.ArrayList;
import java.util.List;

/**
 * @see com.iteaj.iot.client.mqtt.impl.MqttDefaultClientComponent
 */
public class MqttTestMatcher implements MqttDefaultImplProcessor {

    public static final String WillTopic = "/willTopic/#";

    @Override
    public List<MqttTopicSubscription> subscribe(MqttConnectProperties client) {

        List<MqttTopicSubscription> subscriptionList = new ArrayList<>();
        // 订阅所有的遗嘱
        subscriptionList.add(new MqttTopicSubscription(WillTopic, MqttQoS.AT_MOST_ONCE));

        // 订阅对应的Qos等级
        subscriptionList.add(new MqttTopicSubscription(MqttClientTestHandle.AT_MOST_ONCE_TOPIC, MqttQoS.AT_MOST_ONCE));
        subscriptionList.add(new MqttTopicSubscription(MqttClientTestHandle.EXACTLY_ONCE_TOPIC, MqttQoS.EXACTLY_ONCE));
        subscriptionList.add(new MqttTopicSubscription(MqttClientTestHandle.AT_LEAST_ONCE_TOPIC, MqttQoS.AT_LEAST_ONCE));

        return subscriptionList;
    }

    @Override
    public MqttMessageHead buildHeader(byte[] payload, MqttDefaultClientMessage message) {
        if(message.getTopic().contains("willTopic")) {
            String clientId = message.getTopic().split("/")[1];
            return new MqttMessageHead(clientId, clientId, TestProtocolType.WillTop);
        } else {
            JSONObject jsonObject = JSONUtil.parseObj(ByteUtil.bytesToString(payload));
            return new MqttMessageHead(jsonObject.getStr("equipCode")
                    , jsonObject.getStr("messageId"), TestProtocolType.PIReq);
        }
    }

    @Override
    public AbstractProtocol getProtocol(MqttDefaultClientMessage message, ProtocolFactory factory) {
        MqttMessageHead head = message.getHead();
        if(head.getType() == TestProtocolType.PIReq){
            return new MqttSubscribeTestProtocol(message);
        } else if(head.getType() == TestProtocolType.WillTop) {
            return new MqttSubscribeTestProtocol(message);
        } else {
            return null;
        }
    }
}
